package com.wuyu.mini.dubbo.rpc;

import com.wuyu.mini.dubbo.registry.Registry;
import com.wuyu.mini.dubbo.registry.RegistryFactory;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 消费代理
 */
public class ConsumerProxy {
    private static final Logger logger = LoggerFactory.getLogger(ConsumerProxy.class);

    public static <T> T create(final Class<T> interfaceClass) {
        Object o = Proxy.newProxyInstance(interfaceClass.getClassLoader(), new Class[]{interfaceClass}
            , new InvocationHandler() {
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

                    // 封装调用参数
                    RequestDTO requestDTO = new RequestDTO();
                    requestDTO.setClassName(method.getDeclaringClass().getName());
                    requestDTO.setMethodName(method.getName());
                    requestDTO.setTypes(method.getParameterTypes());
                    requestDTO.setParams(args);

                    // 获取服务提供者
                    Registry registry = RegistryFactory.getRegistry();
                    String service = interfaceClass.getName();
                    String serviceAddress = registry.discover(service);

                    // 调用远程调用
                    Object result = RpcFactory.getConsumerService().execute(serviceAddress, requestDTO);
                    return result;
                }
            });
        return (T) o;
    }
}
